package myJs.cps

import cats.effect.SyncIO
import myJs.myPkg.reactHookForm._
import myJs.tool.Tool.messages
import japgolly.scalajs.react.vdom.all._
import japgolly.scalajs.react._
import japgolly.scalajs.react.React.Fragment
import japgolly.scalajs.react.util.EffectCatsEffect._
import myJs.myPkg.Hooks._

import scala.scalajs.js

/** Created by yz on 3/11/2020
  */
object FileSelectInlineCp {

  case class Props(
      fileSelectShow: SyncIO[Unit],
      registerOptions: RegisterOptions = RegisterOptions(),
      label: String,
      name: String,
      value: String = "",
      onChange: String => SyncIO[Unit] = v=>SyncIO{},
      show: Boolean = true,
      inputWidth: Int = 3
  ){
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    val formState = ReactHookForm.useFormState(options =
      UseFormStateOptions(
        name = props.name
      )
    )
    object FTool {}

    val hasErrorCls = if (formState.errors.isDefinedAt(props.name)) "has-error" else ""
    val displayStr = if (props.show) "block" else "none"

    div(
      display := displayStr,
      className := s"form-group ${hasErrorCls}",
      label(className := "control-label col-sm-2", s"${props.label}:"),
      div(
        className := s"col-sm-${props.inputWidth}",
        PureInputCp.Props(
          name = props.name,
          readOnly = true,
          registerOptions = props.registerOptions,
          value = props.value,
          onChange = props.onChange
        ).render
      ),
      div(
        className := "col-sm-3",
        button(
          `type` := "button",
          className := "btn green",
          onClick --> props.fileSelectShow,
          i(className := "fa fa-file"),
          s" ${messages("selectFile")}"
        )
      )
    )

  }

}
